package components

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.gestures.onDrag
import androidx.compose.foundation.layout.*
import androidx.compose.runtime.*
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.PointerIcon
import androidx.compose.ui.input.pointer.pointerHoverIcon
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Dp
import java.awt.Cursor

@OptIn(ExperimentalFoundationApi::class, ExperimentalComposeUiApi::class)
@Composable
fun SplitPanel(
    leftMinSize: Dp,
    rightMinSize: Dp = leftMinSize,
    defaultSplitPosition: Float = 0.5f,
    modifier: Modifier = Modifier,
    left: @Composable () -> Unit,
    right: @Composable () -> Unit,
    splitter: @Composable () -> Unit,
) {
    val leftMinSizePx = with(LocalDensity.current) {
        leftMinSize.toPx()
    }
    val rightMinSizePx = with(LocalDensity.current) {
        rightMinSize.toPx()
    }
    var splitPosition by remember {
        mutableStateOf(0f)
    }
    var letMaxSizePx by remember { mutableStateOf(0f) }
    Row(
        modifier = modifier.fillMaxSize()
            .onSizeChanged {
                letMaxSizePx = it.width.toFloat() - rightMinSizePx
                if (splitPosition == 0f) {
                    splitPosition = defaultSplitPosition * it.width
                }
            }
    ) {
        Box(
            modifier = Modifier
                .width(with(LocalDensity.current) { splitPosition.toDp() })

        ) {
            left()
        }
        Box(
            modifier = Modifier.fillMaxHeight()
                .pointerHoverIcon(icon = PointerIcon(Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR)))
                .onDrag {
                    splitPosition += it.x
                    if (splitPosition <= leftMinSizePx) {
                        splitPosition = leftMinSizePx
                    }
                    if (splitPosition >= letMaxSizePx) {
                        splitPosition = letMaxSizePx
                    }
                }
        ) {
            splitter()
        }
        right()
    }
}